<template>
	<view>
		<view class="musicbackend-everyone" :class="{'has-tab-bar': hasTabBar}">
			<view class="musicbackend-content">
				<img :src="currentSong.current?.imgurl || '../../static/logo.png'" class="musicbackend-head"
					:class="{'rotate-animation': isPlaying, 'rotate-pause': !isPlaying}" alt="" @click="goToPlay()" />
				<view class="musicbackend-body">
					<view class="song-info" v-if="currentSong.current?.name">
						<text class="song-name">{{currentSong.current.name}}</text>
						<text class="song-artist">- {{currentSong.current.artist}}</text>
					</view>
					<view class="progress-container">
						<view class="play-progress-bar">
							<view class="play-progress-loaded" :style="{width: progressWidth + '%'}"></view>
						</view>
						<view class="time-info">
							<text class="new-data">{{formatTime(currentTime)}}</text>
							<text class="all-data">{{formatTime(currentSong.current?.Time || 0)}}</text>
						</view>
					</view>
				</view>
				<view class="musicbackend-controller">
					<text v-if="!isPlaying" class="iconfont icon-bofang6" @click="play"></text>
					<text v-if="isPlaying" class="iconfont icon-zanting3" @click="pause"></text>
					<text class="iconfont icon-liebiao" @click="isshowlist=true"></text>
				</view>
			</view>
		</view>

		<view class="play-list" v-if="isshowlist" :class="{'has-tab-bar': hasTabBar}" ref="playListRef">
			<view class="play-list-nav">
				<view class="play-left">
					播放列表
				</view>
				<view class="play-right">
					<view class="play-way" @click="switchPlayMode">
						<text class="iconfont" :class="playModeIcon"></text>
						{{playModeName}}
					</view>
					<view class="play-del" @click="clearPlaylist">
						<text class="iconfont icon-shanchu6"></text>
						清空
					</view>
				</view>
			</view>
			<view class="play-list-box">
				<view class="play-song-item" v-for="(item, index) in currentSong.playlist" :key="item.id">
					<text class="play-song-name" @click="switchSong(item)">{{item.name}}</text>
					<text class="iconfont icon-shanchu8 play-song-del" @click="removeSong(index)"></text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import '@/common/iconfont.css'
	import audioManager from '@/common/audioManager.js'

	export default {
		name: "musicbackend",
		data() {
			return {
				isshowlist: false,
				currentTime: 0,
				isPlaying: false,
				currentSong: {
					playlist: [],
					current: {}
				},
				playMode: 'loop',
				playModes: {
					loop: {
						name: '循环播放',
						icon: 'icon-xunhuanbofang'
					},
					random: {
						name: '随机播放',
						icon: 'icon-suijibofang'
					},
					single: {
						name: '单曲循环',
						icon: 'icon-danquxunhuan'
					}
				},
				hasTabBar: true
			}
		},
		computed: {
			progressWidth() {
				if (!this.currentSong.current?.Time) return 0;
				return (this.currentTime / this.currentSong.current.Time) * 100;
			},
			playModeIcon() {
				return this.playModes[this.playMode].icon;
			},
			playModeName() {
				return this.playModes[this.playMode].name;
			}
		},
		watch: {
			// 监听页面路由变化
			'$route': {
				immediate: true,
				handler(newRoute) {
					// 更新底部位置
					this.updatePosition();
				}
			}
		},
		created() {
			// 初始化状态
			const currentSongData = audioManager.getCurrentSong();
			const playStatus = audioManager.getPlayStatus();

			this.currentSong = {
				playlist: currentSongData.playlist || [],
				current: currentSongData.current || {}
			};
			this.currentTime = playStatus.currentTime || 0;
			this.isPlaying = playStatus.isPlaying || false;
			this.playMode = playStatus.playMode || 'loop';

			// 注册状态更新回调
			audioManager.onTimeUpdate(this.handleTimeUpdate);
			audioManager.onPlayStatusChange(this.handlePlayStatusChange);
			audioManager.onSongChange(this.handleSongChange);

			// 初始化位置
			this.updatePosition();

			// 使用uni-app的生命周期
			uni.$on('globalClick', this.handleClickOutside);
		},
		beforeDestroy() {
			// 移除uni-app事件监听
			uni.$off('globalClick', this.handleClickOutside);

			// 移除回调
			audioManager.offTimeUpdate(this.handleTimeUpdate);
			audioManager.offPlayStatusChange(this.handlePlayStatusChange);
			audioManager.offSongChange(this.handleSongChange);
		},
		methods: {
			handleTimeUpdate(time) {
				this.currentTime = time;
			},
			handlePlayStatusChange(status) {
				this.isPlaying = status.isPlaying;
				this.playMode = status.playMode;
			},
			handleSongChange(song) {
				this.currentSong = {
					playlist: song.playlist || [],
					current: song.current || {}
				};
			},
			play() {
				audioManager.play();
			},
			pause() {
				audioManager.pause();
			},
			switchPlayMode() {
				const modes = Object.keys(this.playModes);
				const currentIndex = modes.indexOf(this.playMode);
				const nextMode = modes[(currentIndex + 1) % modes.length];
				audioManager.setPlayMode(nextMode);

				uni.showToast({
					title: this.playModes[nextMode].name,
					icon: 'none'
				});
			},
			switchSong(song) {
				audioManager.switchSong(song);
			},
			clearPlaylist() {
				this.currentSong.playlist = [];
				this.currentSong.current = {};
				audioManager.pause();
			},
			removeSong(index) {
				this.currentSong.playlist.splice(index, 1);
				if (this.currentSong.playlist.length === 0) {
					this.currentSong.current = {};
					audioManager.pause();
				}
			},
			formatTime(time) {
				time = Math.floor(time);
				const minutes = Math.floor(time / 60);
				const seconds = time % 60;
				return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
			},
			goToPlay() {
				if (!this.currentSong.current) return;
				uni.navigateTo({
					url: `/pages/play/play?songInfo=${encodeURIComponent(JSON.stringify(this.currentSong))}`
				});
			},
			handleClickOutside(event) {
				// 如果播放列表没有显示，不需要处理
				if (!this.isshowlist) return;

				// 获取播放列表元素
				const playList = this.$refs.playListRef;
				if (!playList) return;

				// 检查点击的元素是否在播放列表内
				// 在uni-app中，我们只需要关闭播放列表
				this.isshowlist = false;
			},
			updatePosition() {
				// 获取当前页面路由
				const pages = getCurrentPages();
				const currentPage = pages[pages.length - 1];
				const route = currentPage?.route || '';

				// 需要显示在底部的页面（有tabBar或特定页面）
				const bottomPages = [
					'pages/index/index',
					'pages/recommend/recommend',
					'pages/my/my'
				];

				// 需要上移的页面（无tabBar的页面）
				const elevatedPages = [
					'pages/search/search',
					'pages/search-result/search-result'
				];

				if (bottomPages.includes(route)) {
					this.hasTabBar = true;
				} else if (elevatedPages.includes(route)) {
					this.hasTabBar = false;
				} else {
					this.hasTabBar = false;
				}
			}
		},
		mounted() {
			// 不再需要添加浏览器特定的事件监听器
			// 改为使用uni-app的生命周期和事件系统
		},
	}
</script>

<style lang="scss">
	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}

	.rotate-animation {
		animation: rotate 8s linear infinite;
	}

	.rotate-pause {
		animation-play-state: paused;
	}

	.musicbackend-everyone {
		width: 100vw;
		height: 50px;
		background-color: rgba(157, 157, 157, 0.3);
		-webkit-backdrop-filter: blur(8px);
		backdrop-filter: blur(8px);
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 999;
		transition: bottom 0.3s ease;
	}

	.musicbackend-everyone.has-tab-bar {
		bottom: 50px;
	}

	.musicbackend-content {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;

		.musicbackend-head {
			margin-left: 10px;
			width: 40px;
			height: 40px;
			border-radius: 50%;
			transition: all 0.3s ease;
			animation: rotate 8s linear infinite paused;

			&.rotate-animation {
				animation-play-state: running;
			}

			&.rotate-pause {
				animation-play-state: paused;
			}
		}

		.musicbackend-body {
			flex: 1;
			height: 40px;
			margin: 0 10px;
			display: flex;
			flex-direction: column;
			justify-content: center;

			.song-info {
				display: flex;
				align-items: center;
				max-width: calc(100% - 20px);
				overflow: hidden;

				.song-name {
					font-size: 14px;
					color: #fff;
					margin-right: 5px;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}

				.song-artist {
					font-size: 12px;
					color: rgba(255, 255, 255, 0.7);
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}
			}

			.progress-container {
				width: 100%;
				padding: 2px 0;

				.play-progress-bar {
					width: 100%;
					height: 2px;
					background-color: rgba(255, 255, 255, 0.3);
					border-radius: 1px;
					position: relative;

					.play-progress-loaded {
						height: 100%;
						background-color: #64b2ac;
						border-radius: 1px;
						transition: width 0.1s linear;
					}
				}

				.time-info {
					display: flex;
					justify-content: space-between;
					margin-top: 2px;

					.new-data,
					.all-data {
						font-size: 10px;
						color: rgba(255, 255, 255, 0.7);
					}
				}
			}
		}

		.musicbackend-controller {
			width: 80px;
			display: flex;
			align-items: center;
			justify-content: space-around;
			margin-right: 10px;

			text {
				font-size: 28px;
				color: #64b2ac;
				cursor: pointer;
			}
		}
	}

	.play-list {
		width: 100vw;
		height: calc(70vh - 100px);
		background-color: #404040;
		position: fixed;
		bottom: 50px;
		left: 0;
		border-radius: 10px 10px 0 0;
		z-index: 998;
		transition: bottom 0.3s ease;
	}

	.play-list.has-tab-bar {
		bottom: 100px;
	}

	.play-list-nav {
		width: 100%;
		height: 50px;
		border-radius: 10px 10px 0 0;
		border-bottom: 1px solid #7a7a7a;
		background-color: #404040;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.play-left {
			margin-left: 10px;
			color: #fff;
		}

		.play-right {
			display: flex;

			.play-way {
				margin-right: 20px;
				color: #fff;
				display: flex;
				align-items: center;
				cursor: pointer;

				.iconfont {
					margin-right: 5px;
					font-size: 16px;
				}
			}

			.play-del {
				margin-right: 10px;
				color: #fff;
			}
		}
	}

	.play-list-box {
		width: 100%;
		height: 550px;
		background-color: #404040;
		overflow-y: auto;

		.play-song-item {
			width: 100%;
			height: 40px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.play-song-name {
				color: #fff;
				max-width: 200px;
				margin-left: 10px;
				font-weight: 300;
				font-family: Serif;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}

			.play-song-del {
				color: #fff;
				font-weight: 100;
				margin-right: 10px;
			}
		}
	}

	// 添加媒体查询，处理没有底部导航栏的页面
	/* #ifdef H5 */
	.no-tab-bar {
		.musicbackend-everyone {
			bottom: 0;
		}

		.play-list {
			bottom: 50px;
			height: calc(70vh - 50px);
		}
	}

	/* #ifdef APP-PLUS */
	.musicbackend-everyone {
		position: absolute;
		top: 0px;
	}
</style>
